package com.demo.rabbitmq.demo01;

import com.demo.rabbitmq.contanst.Constant;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.concurrent.TimeoutException;

/**
 * 发送者
 * @author liangliang
 */
public class Send {

    public static void execute(String host, String username, String password) {
        // 配置连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(host);
        factory.setUsername(username);
        factory.setPassword(password);
        Connection connection = null;
        Channel channel = null;

        try {
            // 建立TCP链接
            connection = factory.newConnection();
            // 在TCP的连接的基础上创建通道
            channel = connection.createChannel();
            // 声明一个队列
            channel.queueDeclare(Constant.QUEUE_NAME, false, false, false, null);
            String message = "Hello RabbitMQ [" +LocalDateTime.now() + "]";

            // 发送消息
            channel.basicPublish("", Constant.QUEUE_NAME, null, message.getBytes("UTF-8"));
            System.out.println("[Send] : " + message);

        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            try {
                assert channel != null;
                channel.close();
                connection.close();
            } catch (IOException | TimeoutException e) {
                e.printStackTrace();
            }
        }

    }
}
